package space.panker916.service;


import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;
import space.panker916.dao.DiscussPostMapper;
import space.panker916.pojo.DiscussPost;
import space.panker916.utils.SensitiveFilter;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostService {
    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max_size}")
    private int maxSize;

    @Value("${caffeine.posts.expire_seconds}")
    private int expireSeconds;

    // 这里的本地缓存其实只是缓存帖子列表中的热门数据

    // 缓存帖子列表
    private LoadingCache<String, List<DiscussPost>> discussPostCache;

    // 缓存帖子总数
    private LoadingCache<Integer, Integer> rowsCache;

    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存
        discussPostCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<>() {
                    @Nullable
                    @Override
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key == null || key.length() == 0)
                            throw new IllegalArgumentException("参数错误，参数为 null 或 长度为0");

                        String[] params = key.split(":");
                        if (params == null || params.length != 2)
                            throw new IllegalArgumentException("参数格式错误，不满足 [offset : limit] 的格式");

                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        // 这里可以增加一个二级缓存：caffeine -> Redis -> mysql

                        logger.info("一级缓存 [caffeine] 正在从 [mysql] 中加载数据！");
                        return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);
                    }
                });

        // 初始化帖子总数缓存
        rowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        logger.info("一级缓存 [caffeine] 正在从 [mysql] 中加载数据！");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });
    }

    // userId == 0 意味着 查的是首页的帖子
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) {
        if (userId == 0 && orderMode == 1)
            return discussPostCache.get(offset + ":" + limit);
//
//        logger.info("一级缓存 [caffeine] 未得到首页的帖子，现在要从 [mysql] 中查询！");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);
    }

    public int findDiscussPostRows(int userId) {
        if (userId == 0)
            return rowsCache.get(userId);

        logger.info("一级缓存 [caffeine] 未得到首页的帖子的总数，现在要从 [mysql] 中查询！");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int addDiscussPost(DiscussPost discussPost) {
        // 转义 HTML 标记 + 过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(HtmlUtils.htmlEscape(discussPost.getTitle())));
        discussPost.setContent(sensitiveFilter.filter(HtmlUtils.htmlEscape(discussPost.getContent())));

        return discussPostMapper.insertDiscussPost(discussPost);
    }

    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    public int updateTypeById(int id, int type) {
        return discussPostMapper.updateTypeById(id, type);
    }

    public int updateStatusById(int id, int status) {
        return discussPostMapper.updateStatusById(id, status);
    }

    public int updateScoreById(int id, double score) {
        return discussPostMapper.updateScoreById(id, score);
    }
}
